import { Component, OnInit } from '@angular/core';
import { JsonApiService } from "app/core/api/json-api.service"; //http请求配置引入
import { Router, ActivatedRoute } from "@angular/router"; //路由引入
import { config } from '../../shared/smartadmin.config';
declare var $: any;
declare var Viewer: any;
@Component({
	selector: 'sa-order-violation-event',
	templateUrl: './order-violation-event.component.html',
	styleUrls:['./order-violation-event.component.css'],
})
export class OrderViolationEventComponent implements OnInit {
	tableData:any = []; //table数据
	totalCount:number = 0; //分页总条数
	curPage:number = 1; //分页当前页
	pageSize:number = 10; //内置的分页每页条数
	formType:string = "add"; // 新增
    initDateRange: any = {
        startTime:'',
        endTime:'',
	}// 时间组件需要渲染的值
	tableParam:any = {
	    companyName: '',
	    companyId: '',
	    carNumber: '',
	    deviceId: '',
	    startTime: '',
	    endTime: '',
	    searchKey: '',//搜索keyword
	}
	constructor(private jsonApiService: JsonApiService, private router: Router,private activatedRoute: ActivatedRoute) {
		activatedRoute.queryParams.subscribe(queryParams => {
			this.curPage = queryParams.nowPage || 1;
		});
	}
	validatorOptions = {
		excluded:[":disabled"],
		feedbackIcons: {
			valid: 'glyphicon glyphicon-ok',
			invalid: 'glyphicon glyphicon-remove',
			validating: 'glyphicon glyphicon-refresh'
		},
		fields: {
			companyName: {
				trigger:"change",
				validators: {
					notEmpty: {
						message: '请选择所属厂区'
					}
				}
			},
			carNumberFrom: {
			    trigger:"change",
				validators: {
					notEmpty: {
						message: '请输入车牌号码'
					}
				}
			},
			orderCode:{
				validators: {
					notEmpty: {
						message: '请输入订单编号'
					}
				}
			},
			emptyLoadTime:{
				validators: {
					notEmpty: {
						message: '请输入订单进厂时间'
					}
				}
			},
		}
	}
	ngOnInit() {
//	    this.initDate();
        this.load();
	}
	// 车辆组件数据回调
    optionSelected(data){
        this.eventForm.carNumber = data.text;
        this.eventForm.deviceId = data.id;
        this.eventForm.companyName =  data.option? data.option.parentName : '';
        this.eventForm.companyId = data.option? data.option.companyId : '';
        $('#carNumberFrom').val(data.text).change();
    }
	// 接收子组件传递过来的数据 
	getSelectTableTime(time){
		this.tableParam.startTime = time.startTime;
		this.tableParam.endTime = time.endTime;
	} 
	// 公司选中回调
    companySelected(data){
        this.tableParam.companyId = data.companyId;
        this.tableParam.companyName = data.companyName;
        this.tableParam.carNumber = data.carNumber;
        this.tableParam.deviceId = data.deviceId;
    }
	//表格搜索
	table_search() {
		this.curPage = 1
		this.tableParam.searchKey = common.stringTrim(this.tableParam.searchKey);
		this.load();
	}
	//刷新
	refresh(){
    	this.load();
    }
	//初始化加载list数据
	load() {
		let data = {
			pageSize:this.pageSize,
			nowPage:this.curPage,
			parameters:{
				companyId: this.tableParam.companyId,
				deviceId: this.tableParam.deviceId,
				startDate: this.tableParam.startTime,
				endDate: this.tableParam.endTime,
				searchKey: this.tableParam.searchKey,
			}
		}
		let reqdata = 'gridPager='+JSON.stringify(data);
		this.jsonApiService.http("orderViolationEvent/orderViolationEventForPage.html", reqdata).subscribe(data => {
			this.tableData = data.exhibitDatas;
			this.totalCount = data.recordCount;
		})
	}
	//分页回调
	paginate(e){
		this.curPage = e.page+1;
		this.pageSize = e.rows;
		this.load();
	}
	// 跳转订单
	jumpRow(row){
	    let queryParams = {
            orderCode: row.orderCode,
            startTime: row.emptyLoadTime,
            endTime: row.updateTime,
        }
        let BaseURL = window.location.protocol + '//' + window.location.hostname + ':' + window.location.port;
        common.setCookie('jumpFromOrderViolationEvent', JSON.stringify(queryParams));
        window.open(BaseURL + '#/data-statistics/task/order-management');
	}
	/**
	 *   项目事件新增编辑模块===========================================================================================
	 */
	eventForm:any = {
		id: "",
		companyName: "",
		companyId: "",
		carNumber: "",
		deviceId: "",
		orderCode: "",
		emptyLoadTime: "",
		punishImage: "",
		violationImage: "",
		remark: ""
	}
	// 初始化时间插件
//  initDate(){
//      let that=this;
//      return new Promise(function(resolve,error){
//          System.import('assets/js/datepicker/js/bootstrap-datetimepicker.min.js').then(() => {
//              System.import('assets/js/datepicker/locales/bootstrap-datetimepicker.zh-CN.js').then(() => {
//                  $("#eventTime").datetimepicker({ //时间插件
//                      format: "yyyy-mm-dd",
//                      language: "zh-CN",
//                      autoclose: true,
//                      minView: 2,
//                  })
//                  resolve();
//              })
//          })
//      });
//  }
	// 添加用户界面打开
	showAddUserModal(modal){
		this.formType = 'add'
		let that = this;
		this.imageInfo = {
			punishImage: [],
            violationImage: [],
		}
		this.eventForm = {
			id: "",
            companyName: "",
            companyId: "",
            carNumber: "",
            deviceId: "",
            orderCode: "",
            emptyLoadTime: "",
            punishImage: "",
            violationImage: "",
            remark: ""
		}
		var str=$("<span class='select2-selection__placeholder'>请选择</span>");
		$('#carNumberFrom').val("");
		$('#carSelect2').val("");
		$("#select2-carSelect2-container").empty();
		$("#select2-carSelect2-container").attr("title","");
		$("#select2-carSelect2-container").prepend(str);
		modal.show();
	}
	// 编辑
	editRow(row,modal){
		this.formType = 'update';
		for(let key in this.eventForm){
		    this.eventForm[key] = row[key];
		}
		$('#carNumberFrom').val(row.carNumber).change();
        $('#companyNameForm').val(row.companyName).change();
//		$("#select2-carSelect2-container").html('<span class="select2-selection__clear">×</span>' + row.carNumber)
		this.imageInfo = {
			punishImage: [],
			violationImage: [],
		}
		//显示图片
		this.imageInfo.punishImage = row.punishImage? row.punishImage.split(",") : [];
		this.imageInfo.violationImage = row.violationImage? row.violationImage.split(",") : [];
		modal.show();
	}
	//新增或者编辑公司选中回调
	companySelectedForm(data) {
		this.eventForm.companyId = data.companyId || '';
		this.eventForm.companyName = data.companyName;
	}
	// 添加用户界面关闭
	closeProjectEventModal(modal){
		$("#projectEventForm").data('bootstrapValidator').resetForm();
		modal.hide();
	}
	// 提交
	projectEventSubmit(modal){
		$('#projectEventForm').bootstrapValidator('validate'); //开启验证
		let isValid = $('#projectEventForm').data('bootstrapValidator').isValid();  //验证是否通过
		if(isValid){
		    let valid = common.checkDateFormat(this.eventForm.emptyLoadTime);
            if(!valid){
                this.jsonApiService.message('进厂时间格式不正确');
                return
            }
			this.eventForm.punishImage = this.imageInfo.punishImage.join(",");
			this.eventForm.violationImage = this.imageInfo.violationImage.join(",");
			let Url:string = 'orderViolationEvent/addOrderViolationEvent.html';
			if (this.formType == "update") {
			    Url = 'orderViolationEvent/editOrderViolationEvent';
			}
			this.jsonApiService.http_obj(Url, this.eventForm).subscribe(data => {
			    if(data.success){
			        this.closeProjectEventModal(modal);
                    this.load();
			    }
                this.jsonApiService.message(data.message);
            })
		}
	}
	// 删除
	delRow(row) {
		this.jsonApiService.confirm_message("此操作将永久删除数据,确认要删除?").then(() => {
			let reqdata = 'id=' + row.id;
			this.jsonApiService.http("orderViolationEvent/deleteById.html", reqdata).subscribe(data => {
				this.jsonApiService.message(data.message);
				this.load();
			})
		})
	}
	/**
	 * 图片的方法
	 */
	imgLocalList:any = [];
	isViewer:boolean = false; //默认隐藏
	isViewer1:boolean = false; //默认隐藏
	//显示图片组件
	viewer1: any = '';
	imageInfo : any = {
        punishImage: [],
        violationImage: [],
	}
	
	 //显示图片组件
	 viewer: any = '';
	 fileList: File = null;
	
	bigImgClick(ele){
		if(this.isViewer && $(".viewer-container").length >0){
			System.import('assets/js/viewer/viewer.js').then(
				()=>{System.import('assets/js/viewer/bootstrap.bundle.min.js').then(
					()=>{System.import('assets/js/viewer/viewer.css').then(()=>{
						this.showImg(ele);
					})
				})
			})
		}else{
			this.showImg(ele);
		}
	}
	showImg(ele){
		var imgList = $("."+ele)[0];
		this.viewer = new Viewer(imgList, {
			url: 'src',
			title: function (image) {
				return image.alt + ' (' + (this.index + 1) + '/' + this.length + ')' ; 
			},
		});
		this.isViewer = true
	}
	//上传多张
	multifileChange(files: FileList,describe){
		if(this.isViewer && $(".viewer-container").length >0){
			this.viewer.destroy();
		}
		let multfileList = files;
        var reqdata = new FormData();
		reqdata.append('describe',describe);
		reqdata.append('businessType', '3');
		reqdata.append('type', '2'); //type 1获取相对路径  2获取绝对路径
		for(var i = 0; i < multfileList.length; i++){
			this.fileList = multfileList[i];
			const isJPG = this.fileList.type === 'image/jpeg'|| this.fileList.type === 'image/jpg'|| this.fileList.type === 'image/png';
			if (!isJPG) {
    			this.jsonApiService.message('上传图片只能是 png, jpg, jpeg 格式!');
    			return;
			}
			reqdata.append('files',multfileList[i]);
		}
		this.jsonApiService.form_http("fileUpload/upload.html",reqdata).subscribe(data=> {
			if(data.success){
			    if(describe == '客户处罚图片'){
			        for(let item of data.data){
			            this.imageInfo.punishImage.push(item);
			        }
			    }else if(describe == '违流订单图片'){
			        for(let item of data.data){
                        this.imageInfo.violationImage.push(item);
                    }
			    }
			}
		})
		for(let k = 0; k < $(".up").length; k++) {
			$(".up")[k].value = null;
		}
    }
	
	//删除图片
	deleteImg(describe,i){
        if(describe == '客户处罚图片'){
            this.imageInfo.punishImage.splice(i,1);
        }else if(describe == '违流订单图片'){
            this.imageInfo.violationImage.splice(i,1);
        }
		if(this.isViewer && $(".viewer-container").length >0){
			this.viewer.destroy();
		}
    }
	// 关闭图片查看
	closeImgModal1(modal){
		modal.hide();
		this.imgLocalList = [];
	}

	// 点击Table中的查看图片
	imgName:string = '';
	showImg1(src,modal,describe){
	    this.imgName = describe;
		this.imgLocalList = [];
		this.imgLocalList = src.split(",");
		modal.show();
		if(this.isViewer1 && $(".viewer-container").length > 0){
			this.viewer1.destroy();
		}
	}
	bigimg(){
		if(this.isViewer1 && $(".viewer-container").length >0){
			System.import('assets/js/viewer/viewer.js').then(
				()=>{System.import('assets/js/viewer/bootstrap.bundle.min.js').then(
					()=>{System.import('assets/js/viewer/viewer.css').then(()=>{
						this.showBigImg();
					})
				})
			})
		}else{
			this.showBigImg();
		}
	}
	showBigImg(){
		var that = this;
		var imgList = $(".imagesInfo1")[0];
		this.viewer1 = new Viewer(imgList, {
			url: 'src',
			title: function (image) {
				return image.alt + ' (' + (this.index + 1) + '/' + this.length + ')' ; 
			},
		});
		that.isViewer1 = true
	}
}